package com.example.controller;


import com.example.common.Code;
import com.example.common.Result;
import com.example.domain.ChangePwd;
import com.example.domain.Staff;
import com.example.domain.User;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author luo
 * 登录、注册、修改密码
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result login(@RequestBody User user, HttpServletRequest request) {

        System.out.println("login---success!");
        boolean userByName = userService.findUserByName(user);
        System.out.println(userByName);
        request.getSession().setAttribute("username",userByName);
        request.getSession().setAttribute("password", userByName);
        return new Result(userByName ? Code.LOGIN_OK : Code.LOGIN_ERR, userByName, null);
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        System.out.println("logout----");
        request.getSession().removeAttribute("username");
//        request.getSession().invalidate(); //设置session 失效
        String msg = "退出登录";
        return new Result(Code.LOGIN_ERR,null,msg);

    }


    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        boolean findname = userService.findName(user);
        Integer code = findname ? Code.INSERT_ERR : Code.INSERT_OK;
        String msg = findname ? "用户已存在,请重试！" : "";
        return new Result(code, findname, msg);
    }

    @PutMapping("/changPwd")
    public Result changePwd(@RequestBody ChangePwd changePwd) {
        System.out.println(changePwd);
        boolean findname = userService.changePwd(changePwd);
        Integer code = findname ? Code.UPDATE_OK : Code.UPDATE_ERR;
        String msg = findname ? "" : "用户名或者密码错误，请重试！";
        return new Result(code, findname, msg);
    }
}

